﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.SQLite;

namespace DatabaseUtils {
  /// <summary>
  /// Connections helper class
  /// </summary>
  public class Connections {

    public enum ConnectionStrings {
      SqLiteConnection
    }

    /// <summary>
    /// Gets the connection string.
    /// </summary>
    /// <param name="connectionString">The connection string.</param>
    /// <returns></returns>
    public static ConnectionStringSettings GetConnectionString( ConnectionStrings connectionString ) {

      if ( ConfigurationManager.ConnectionStrings.Count == 0 ) {
        throw new InvalidOperationException( "No ConnectionStrings found in .config" );
      }


      ConnectionStringSettings setting = ConfigurationManager.ConnectionStrings[ connectionString.ToString() ];
      if ( setting == null ) {
        throw new InvalidOperationException( "ConnectionString : " + connectionString.ToString()
          + " not found." );
      }

      return setting;
    }

    /// <summary>
    /// Gets the connection string.
    /// </summary>
    /// <param name="connectionStringName">Name of the connection string.</param>
    /// <returns></returns>
    public static ConnectionStringSettings GetConnectionString( string connectionStringName ) {

      if ( ConfigurationManager.ConnectionStrings.Count == 0 ) {
        throw new InvalidOperationException( "No ConnectionStrings found in .config" );
      }


      ConnectionStringSettings setting = ConfigurationManager.ConnectionStrings[ connectionStringName ];
      if ( setting == null ) {
        throw new InvalidOperationException( "ConnectionString : " + connectionStringName
          + " not found." );
      }

      return setting;
    }

    /// <summary>
    /// Creates the connection.
    /// </summary>
    /// <param name="connectionStringName">The connection.</param>
    /// <returns></returns>
    public static SQLiteConnection CreateConnection( string connectionStringName ) {
      SQLiteConnection conn = new SQLiteConnection( GetConnectionString( connectionStringName ).ConnectionString );
      conn.Open( );
      return conn;
    }

    /// <summary>
    /// Creates the connection.
    /// </summary>
    /// <param name="connectionString">The connection.</param>
    /// <returns></returns>
    public static SQLiteConnection CreateConnection( ConnectionStrings connectionString ) {
      SQLiteConnection conn = new SQLiteConnection( GetConnectionString( connectionString ).ConnectionString );
      conn.Open( );
      return conn;
    }
  }
}
